import { ReloadOutlined } from '@ant-design/icons'
import { Popconfirm, Table, message, Button } from 'antd'
import services from '@/services'
import { BatchApplyStatus } from '@/services/features/group-batch-apply'
import type { BatchApplyConfig } from '@/services/features/group-batch-apply'
import EditConfigModal from './edit'
import ConfigTasksModal from './tasks'
import './Content.module.less'

export default function Content() {
  const [configs, setConfigs] = useState<BatchApplyConfig[]>([])
  const [loading, setLoading] = useState(false)
  const loadConfigs = useCallback(async () => {
    setLoading(true)
    const res = await services.features.groupBatchApply.loadConfigs()
    if (res.success) setConfigs(res.data)
    else void message.warning('获取任务列表失败')
    setLoading(false)
    return res.success
  }, [])

  const [switching, setSwitching] = useState(false)
  const switchStatus = useCallback(
    async (config: BatchApplyConfig, status: BatchApplyStatus) => {
      setSwitching(true)

      const res = await services.features.groupBatchApply.addOrUpdateConfig({ ...config, status })
      if (res.success) void message.success('操作成功')
      else void message.warning(`操作失败：${res.error}`)

      await loadConfigs()

      setSwitching(false)
    },
    [loadConfigs],
  )

  const [removing, setRemoving] = useState(false)
  const remove = useCallback(
    async (id: number) => {
      setRemoving(true)

      const res = await services.features.groupBatchApply.removeConfig(id)
      if (res.success) void message.success('删除成功')
      else void message.warning(`删除失败：${res.error}`)

      await loadConfigs()

      setRemoving(false)
    },
    [loadConfigs],
  )

  const [showingDetail, setShowingDetail] = useState<BatchApplyConfig | null>(null)

  const [editing, setEditing] = useState<false | true | BatchApplyConfig>(false) // true: 新建  BatchApplyConfig: 编辑
  const finishEdit = useCallback(() => {
    setEditing(false)
    void loadConfigs()
  }, [loadConfigs])

  const blocking = loading || removing || switching

  useEffect(() => {
    void loadConfigs()
    const intervalId = setInterval(async () => loadConfigs(), 15 * 1000) // 定时刷新任务列表，因为加人任务的状态随时可能变化
    return () => clearInterval(intervalId)
  }, [loadConfigs])

  const renderStatus = useCallback((config: BatchApplyConfig) => {
    if (config.status === BatchApplyStatus.Idle) return '未开始'
    if (config.status === BatchApplyStatus.Applying) return '正在加人'
    if (config.status === BatchApplyStatus.Pause) return '暂停'
    return '已完成'
  }, [])

  const renderActions = useCallback(
    (config: BatchApplyConfig) => {
      return <>
        {config.status === BatchApplyStatus.Idle || config.status === BatchApplyStatus.Pause ? (
          <Button
            type="link"
            loading={switching}
            onClick={async () => switchStatus(config, BatchApplyStatus.Applying)}
          >
            启动
          </Button>
        ) : null}

        {config.status === BatchApplyStatus.Applying ? (
          <Button
            type="link"
            loading={switching}
            onClick={async () => switchStatus(config, BatchApplyStatus.Pause)}
          >
            暂停
          </Button>
        ) : null}

        {config.status === BatchApplyStatus.Idle || config.status === BatchApplyStatus.Pause ? (
          <Button type="link" onClick={() => setEditing(config)}>
            修改
          </Button>
        ) : null}

        <Button type="link" onClick={() => setShowingDetail(config)}>
          明细数据
        </Button>
        <Popconfirm title="确定要删除此任务吗？" onConfirm={async () => remove(config.id)}>
          <Button type="link" danger>
            删除
          </Button>
        </Popconfirm>
      </>
    },
    [remove, switchStatus, switching],
  )

  return <>
    <header>
      <div styleName="tips">群内批量加人提供批量向指定群内成员发送好友申请的功能。</div>
      <div styleName="header-actions">
        <Button disabled={blocking} type="primary" onClick={() => setEditing(true)}>
          新建批量加人任务
        </Button>
        <a onClick={loadConfigs}>
          <ReloadOutlined />
          刷新
        </a>
      </div>
    </header>

    <Table<BatchApplyConfig>
      rowKey="id"
      dataSource={configs}
      scroll={{ y: 300 }}
      pagination={false}
      loading={blocking}
    >
      <Table.Column<BatchApplyConfig> title="任务名称" width={180} dataIndex="name" />
      <Table.Column<BatchApplyConfig> title="状态" key="status" width={80} render={renderStatus} />
      <Table.Column<BatchApplyConfig>
        title="已申请"
        width={80}
        align="center"
        dataIndex="applyedCount"
      />
      <Table.Column<BatchApplyConfig>
        title="已通过"
        width={80}
        align="center"
        dataIndex="passedCount"
      />
      <Table.Column<BatchApplyConfig>
        title="操作"
        key="actions"
        width={160}
        styleName="actions"
        render={renderActions}
      />
    </Table>

    <ConfigTasksModal config={showingDetail ?? undefined} onClose={() => setShowingDetail(null)} />
    <EditConfigModal editing={editing} onFinish={finishEdit} />
  </>
}
